//
//  GolfFriendViewController.m
//  GolfFriend
//
//  Created by vescky on 13-11-30.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "GolfFriendViewController.h"
#import "GolfFriendCircleCell.h"
#import "UserSession.h"
#import "AppsEngine.h"
#import "DXAlertView.h"
#import "UserSession.h"
#import "GFVOParser.h"
#import "SVProgressHUD.h"
#import "CacheDaoForCircleContent.h"
#import "DateUtility.h"

@interface GolfFriendViewController ()<GolfFriendCircleCellDelegate> {
    GolfFriendCircleCell *sampleCell;
    CacheDaoForCircleContent *contentCacheManager;
    bool isPersonalPage;
}

@end

@implementation GolfFriendViewController
@synthesize articlesArray,delegate,hostUserId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(articlePublishedNotificationDidRecieve:) name:Notification_Article_Published object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(articleCommentedNotificationDidRecieve:) name:Notification_Article_Comment_Published object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(articleDeletedNotificationDidRecieve:) name:Notification_Article_Deleted object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self initData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData {
    if (hostUserId && hostUserId.length > 0) {
        isPersonalPage = YES;
    }
    
    currentPage = 1;
    
    labelDate.text = getStringFromDate(@"yyyy-MM-dd", [NSDate date]);
    labelWeek.text = getEnglishWeekdayFromDate([NSDate date]);
    
    //读取缓存数据，再请求网上数据
    if (!contentCacheManager) {
        contentCacheManager = [CacheDaoForCircleContent shareCacheDaoForCircleContent];
    }
    NSMutableArray *cDataArray = [contentCacheManager getCacheDataLimitRow:NSMakeRange(0, 20)];
    
    if (isPersonalPage) {
        cDataArray = [contentCacheManager getArticlesPublishedByUser:hostUserId range:NSMakeRange(0, 20)];
    }
    
    if (cDataArray && [cDataArray count] > 0) {
        [articlesArray removeAllObjects];
         articlesArray = [self sortArrayByRecordIdDesc:cDataArray];
    }
    else {
        //显示没有数据的页面
        [self.view addSubview:noDataView];
    }
    
    //网上请求数据
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                 [NSString stringWithFormat:@"%d",1],@"page", nil];
    
    if (hostUserId) {
        [dict setObject:hostUserId forKey:@"userId"];
    }
    else {
        if ([[UserSession shareUserSession] getUserId]) {
            [dict setObject:[[UserSession shareUserSession] getUserId] forKey:@"userId"];
        }
    }
    
    [[AppsEngine shareAppsEngine] submitRequest:(isPersonalPage ? @"gfGetUserCircles" : @"gfGetCircleContent") param:dict onCompletion:^(id jsonResponse) {
        
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            NSLog(@"刷新成功");
            currentPage = 1;
            NSMutableArray *arr1 = [[GFVOParser shareParser] paseDataForCircleContentArray:jsonResponse];
            if (!arr1 || [arr1 count] <= 0) {
                NSLog(@"没有数据了...");
            }
            else {
                [articlesArray removeAllObjects];
                articlesArray = [self sortArrayByRecordIdDesc:arr1];
                [contentCacheManager updateCacheDataWithCircleContentArray:articlesArray];
                [self refreshTableView];
            }
        }
        if ([delegate respondsToSelector:@selector(refreshContentDidFinish)]) {
            [delegate refreshContentDidFinish];
        }
        
        if (isPersonalPage) {
            [self refreshTableView];
        }
    } onError:^(NSError *error) {
        NSLog(@"联网失败");
//        if ([delegate respondsToSelector:@selector(refreshContentDidFinish)]) {
//            [delegate refreshContentDidFinish];
//        }
        if (isPersonalPage) {
            [self refreshTableView];
        }
//        DXAlertView *dAlert = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"暂无网络连接!" leftButtonTitle:nil rightButtonTitle:@"确定"];
//        [dAlert show];
    } method:@"GET"];
}

- (void)initView {
    
}


//获取Cell的高度
- (float)getCellHeightWithContent:(CircleContentVO*)cVo {
    if (!sampleCell) {
        sampleCell = [[[NSBundle mainBundle] loadNibNamed:@"GolfFriendCircleCell" owner:self options:nil] objectAtIndex:0];
    }
    return [sampleCell getContentHeight:cVo];
}


//将数组内容存进去
- (void)saveCacheData {
    
}

- (NSMutableArray*)sortArrayByRecordIdDesc:(NSMutableArray*)_arr {
    NSArray *sortedArr = [_arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        CircleContentVO *cVo1 = (CircleContentVO*)obj1;
        CircleContentVO *cVo2 = (CircleContentVO*)obj2;
        
        if ([cVo1.articleId integerValue] < [cVo2.articleId integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        else if ([cVo1.articleId integerValue] > [cVo2.articleId integerValue]){
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    return [[NSMutableArray alloc] initWithArray:sortedArr];
}

- (NSMutableArray*)removeSameItemInArray:(NSMutableArray*)_arr {
    NSMutableDictionary *rDict = [[NSMutableDictionary alloc] init];
    for (int i = 0; i < [_arr count]; i++) {
        CircleContentVO *cVo = [_arr objectAtIndex:i];
        [rDict setObject:cVo forKey:cVo.articleId];
    }
    
    NSMutableArray *rArr = [[NSMutableArray alloc] init];
    NSEnumerator *_enum = [rDict keyEnumerator];
    for (NSString *key in _enum) {
        [rArr addObject:[rDict objectForKey:key]];
    }
    return rArr;
}

- (void)articlePublishedNotificationDidRecieve:(NSNotification*)notification {
    if ([notification object]) {
        [articlesArray insertObject:[notification object] atIndex:0];
    }
    
    [self refreshTableView];
}

- (void)articleCommentedNotificationDidRecieve:(NSNotification*)notification {
    if ([notification object]) {
        CircleContentVO *cVo = [notification object];
        for (int i = 0; i < [articlesArray count]; i++) {
            CircleContentVO *c1 = [articlesArray objectAtIndex:i];
            if ([c1.articleId isEqualToString:cVo.articleId]) {
                [articlesArray replaceObjectAtIndex:i withObject:c1];
            }
        }
    }
    [self refreshTableView];
}

- (void)articleDeletedNotificationDidRecieve:(NSNotification*)notification {
    if ([notification object]) {
        CircleContentVO *cVo = [notification object];
        for (int i = 0; i < [articlesArray count]; i++) {
            CircleContentVO *c1 = [articlesArray objectAtIndex:i];
            if ([c1.articleId isEqualToString:cVo.articleId]) {
                [articlesArray removeObject:cVo];
                [[CacheDaoForCircleContent shareCacheDaoForCircleContent] deleteArticleContent:cVo];
                [SVProgressHUD showSuccessWithStatus:@"删除成功!"];
                break;
            }
        }
    }
    [self performSelector:@selector(refreshTableView) withObject:nil afterDelay:1.0];
}

#pragma mark - public
- (IBAction)btnAddNewArticle:(id)sender {
    
}

- (float)getTableViewHeightWithDataArray:(NSArray*)_arr {
    if (!_arr || [_arr count] <= 0) {
        _arr = articlesArray;//默认参数
    }
    float tbHeight = 0;
    for (int i = 0; i < [_arr count]; i++) {
        tbHeight = tbHeight + [self getCellHeightWithContent:[_arr objectAtIndex:i]];
    }
    //无数据，返回无数据的高度
    if (tbHeight <= 0) {
        return noDataView.frame.size.height;
    }
    return tbHeight+tbView.frame.origin.y-1;
}

//下拉刷新内容
- (void)refreshContent {
    NSLog(@">>>>>>>>>>>  Refresh begin <<<<<<<<<<<<<<");
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                 [NSString stringWithFormat:@"%d",1],@"page", nil];
    
    if (hostUserId) {
        [dict setObject:hostUserId forKey:@"userId"];
    }
    else {
        if ([[UserSession shareUserSession] getUserId]) {
            [dict setObject:[[UserSession shareUserSession] getUserId] forKey:@"userId"];
        }
    }
    
    [[AppsEngine shareAppsEngine] submitRequest:(isPersonalPage ? @"gfGetUserCircles" : @"gfGetCircleContent") param:dict onCompletion:^(id jsonResponse) {
        
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
             NSLog(@"刷新成功");
            currentPage = 1;
            [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
            NSMutableArray *arr1 = [[GFVOParser shareParser] paseDataForCircleContentArray:jsonResponse];
            if (!arr1 || [arr1 count] <= 0) {
                NSLog(@"没有数据了...");
            }
            else {
                [articlesArray removeAllObjects];
                [articlesArray addObjectsFromArray:arr1];
                articlesArray = [self removeSameItemInArray:articlesArray];
                articlesArray = [self sortArrayByRecordIdDesc:articlesArray];
                [contentCacheManager updateCacheDataWithCircleContentArray:articlesArray];
                [self refreshTableView];
            }
        }
        else {
            NSLog(@"刷新失败");
            [SVProgressHUD showErrorWithStatus:@"刷新失败"];
        }
        
        if ([delegate respondsToSelector:@selector(refreshContentDidFinish)]) {
            [delegate refreshContentDidFinish];
        }
        
        if (isPersonalPage) {
            [self refreshTableView];
        }
        
    } onError:^(NSError *error) {
        NSLog(@"联网失败");
        if ([delegate respondsToSelector:@selector(refreshContentDidFinish)]) {
            [delegate refreshContentDidFinish];
        }
        if (isPersonalPage) {
            [self refreshTableView];
        }
//        DXAlertView *dAlert = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"暂无网络连接!" leftButtonTitle:nil rightButtonTitle:@"确定"];
//        [dAlert show];
    } method:@"GET"];
}

//上拉加载更多内容
- (void)loadMoreContent {
    NSLog(@">>>>>>>>>>>  Load More begin <<<<<<<<<<<<<<");
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                 [NSString stringWithFormat:@"%d",currentPage + 1],@"page", nil];
    if (isPersonalPage) {
        [dict setObject:hostUserId forKey:@"userId"];
    }
    
    if (hostUserId) {
        [dict setObject:hostUserId forKey:@"userId"];
    }
    else {
        if ([[UserSession shareUserSession] getUserId]) {
            [dict setObject:[[UserSession shareUserSession] getUserId] forKey:@"userId"];
        }
    }
    
    [[AppsEngine shareAppsEngine] submitRequest:(isPersonalPage ? @"gfGetUserCircles" : @"gfGetCircleContent") param:dict onCompletion:^(id jsonResponse) {
        
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            NSLog(@"加载成功");
            NSMutableArray *arr1 = [[GFVOParser shareParser] paseDataForCircleContentArray:jsonResponse];
            if (!arr1 || [arr1 count] <= 0) {
                NSLog(@"已加载到最后一页");
                [SVProgressHUD showSuccessWithStatus:@"已加载到最后一页"];
            }
            else {
                currentPage++;
                [articlesArray addObjectsFromArray:arr1];//加入原数组中
                articlesArray = [self removeSameItemInArray:articlesArray];
                articlesArray = [self sortArrayByRecordIdDesc:articlesArray];
                [contentCacheManager updateCacheDataWithCircleContentArray:articlesArray];
                [self refreshTableView];
            }
        }
        else {
            NSLog(@"加载更多失败");
            [SVProgressHUD showErrorWithStatus:@"加载更多失败!"];
        }
        
        if ([delegate respondsToSelector:@selector(loadMoreContentDidFinish)]) {
            [delegate loadMoreContentDidFinish];
        }
        
        if (isPersonalPage) {
            [self refreshTableView];
        }
    } onError:^(NSError *error) {
        NSLog(@"联网失败");
        if ([delegate respondsToSelector:@selector(loadMoreContentDidFinish)]) {
            [delegate loadMoreContentDidFinish];
        }
        if (isPersonalPage) {
            [self refreshTableView];
        }
//        DXAlertView *dAlert = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"暂无网络连接!" leftButtonTitle:nil rightButtonTitle:@"确定"];
//        [dAlert show];
    } method:@"GET"];
}


- (void)refreshTableView {
    if (articlesArray && [articlesArray count] > 0) {
       CGRect tbRect = tbView.frame;
        tbRect.size.height = [self getTableViewHeightWithDataArray:articlesArray];
        [tbView setFrame:tbRect];
        [noDataView removeFromSuperview];
        [tbView reloadData];
    }
    else {
        if (isPersonalPage) {
            labelNoData.text = @"该用户尚未发表过文章~~";
        }
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [articlesArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"GolfFriendCircleCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"GolfFriendCircleCell" owner:self options:nil] objectAtIndex:0];
    }
    
    if([cell respondsToSelector:@selector(setDataInfo:)]){
        [cell performSelector:@selector(setDataInfo:) withObject:[articlesArray objectAtIndex:indexPath.row]];
    }
    if([cell respondsToSelector:@selector(setDelegate:)]){
        [cell performSelector:@selector(setDelegate:) withObject:self];
    }
    
    [cell setTag:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self getCellHeightWithContent:[articlesArray objectAtIndex:indexPath.row]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"GolfFriend Cell selected:%d",indexPath.row);
}

#pragma mark - GolfFriendCircleCellDelegate
- (void)cell2ButtonPressed:(id)sender withObject:(id)ccVo {
    CircleContentVO *newCvo = (CircleContentVO*)ccVo;
    UIButton *btn = (UIButton*)sender;
    if (btn.tag == 201) {
        //201 赞
        for (int i = 0; i < [articlesArray count]; i++) {
            CircleContentVO *cVo = [articlesArray objectAtIndex:i];
            if ([cVo.articleId isEqualToString:newCvo.articleId]) {
                [articlesArray replaceObjectAtIndex:i withObject:newCvo];
                [tbView reloadData];
                return;
            }
        }
    }
    if ([self.delegate respondsToSelector:@selector(circleCellButtonPressed:withObject:)]) {
        [self.delegate circleCellButtonPressed:sender withObject:ccVo];
    }
}


@end
